﻿using FlyIL.Misc;
using FlyIL.Trace;
using System.Collections.Generic;

namespace FlyIL.Optimizer;



class AlterEspPass : SimplfyRoot
{

    PopPass pop_pass;


    public override bool IsMatch(Context con, Inst node, ExpByTrace expression = null)
    {
        var inst = node;
        return inst.O1.IsRegister && inst.O1.Base == con.CodeSp;
    }

    /// <summary>
    /// 修改 esp 
    /// </summary>
    public override void Do(Context con, Inst node, ExpByTrace expression = null)
    {
        int? val = node.SpVariety;
        if (val == null)
            return;

        /// 相当于 一个 pop 
        if (val > 0)
        {

            /// 寻找 mov xxx, [esp] 

            var mov_nodes = con.FindUseStack(node);
            if (mov_nodes != null && mov_nodes.Count > 0)
            {
                pop_pass ??= new PopPass();

                /// 转换为 一条或 多条 pop 语句 
                /// todo: 此处还需要 更多验证 

                node.nop();
                foreach (var u in mov_nodes)
                {
                    u.pop(u.O1);
                }

                //pop_pass.Do(con, node);
            }
            else
            {

                /// 再去寻找 push 节点 

                var pnode = con.FindThePush(node);
                if (pnode != null)
                {
                    con.Nop_push_pop(pnode, node);
                }
                else
                {

                    var op = Operand.Make(2, RegCode.esp, 0);

                    var pushs = con.FindPushs(node, ref op);


                    var found = con.Nop_Multi_Pops(node, val);
                    if (found == null)
                    {
                        ;
                    }
                }

            }
        }
    }
}


